<script setup>
import { useAppStore, useWMTSStore } from '@/stores'
import ExceptionLogger from '@/utils/errorHandler'
import { useBoolean } from '@/hooks/useBoolean'

const appStore = useAppStore()
const wmtsStore = useWMTSStore()
const selectedValue = ref('选择要加载的WMS图层')
const wmtsURL = ref('')
const options = ref([])
const loading = ref(false)
const windowWidth = ref(window.innerWidth)
const windowHeight = ref(window.innerHeight)
const adaptHeight = appStore.showTabs ? (appStore.showFooter ? ref(387) : ref(427)) : appStore.showFooter ? ref(427) : ref(472)
const { bool: addLoading, setTrue: startLoading, setFalse: endLoading } = useBoolean(false)
const computedHeight = computed(() => windowHeight.value - adaptHeight.value)

const handleResize = () => {
  windowWidth.value = window.innerWidth
  windowHeight.value = window.innerHeight
}

const handleUpdateValue = async (_, option) => {
  startLoading()
  try {
    wmtsStore.setCurrentTileMatrixSet(option.label)
    await wmtsStore.setSuperMap3DAddCode()
    while (smViewer_wmts.imageryLayers._layers.length > 2) {
      smViewer_wmts.imageryLayers.remove(smViewer_wmts.imageryLayers._layers[2])
    }
    eval(wmtsStore.supermap3dAddCode)
  } catch (error) {
    ExceptionLogger.wmtsHandleException(error)
  } finally {
    endLoading()
  }
}

const load = async () => {
  if (!ExceptionLogger.isValidURL(wmtsURL.value)) return ExceptionLogger.logException('请输入正确的 URL 地址')
  loading.value = true
  startLoading()
  try {
    await wmtsStore.initWMTSInfo(wmtsURL.value)
    await wmtsStore.setSuperMap3DAddCode()
    while (smViewer_wmts.imageryLayers._layers.length > 2) {
      smViewer_wmts.imageryLayers.remove(smViewer_wmts.imageryLayers._layers[2])
    }
    eval(wmtsStore.supermap3dAddCode)
  } catch (error) {
    ExceptionLogger.wmtsHandleException(error)
  } finally {
    loading.value = false
    endLoading()
  }
}

function initViewer() {
  window.smViewer_wmts = new SuperMap3D.Viewer('SuperMap3DContainer')
  // 星图地球云影像
  smViewer_wmts.imageryLayers.addImageryProvider(
    new SuperMap3D.UrlTemplateImageryProvider({
      // url: 'https://tiles1.geovisearth.com/base/v1/vec/{z}/{x}/{y}?format=png&tmsIds=w&token=68a7e91671f4ff9d03068c85ec2660af69558c60929c0e644aba6a342735e2dc', //服务地址
      url: 'https://tiles{s}.geovisearth.com/base/v1/img/{z}/{x}/{y}?format=webp&token=68a7e91671f4ff9d03068c85ec2660af69558c60929c0e644aba6a342735e2dc', //服务地址
      maximumLevel: 18,
      subdomains: '123'
    })
  )
}

watch(
  () => wmtsStore.wmtsInfo.mapLayer,
  () => {
    if (Array.isArray(wmtsStore.wmtsInfo.mapLayer) && wmtsStore.wmtsInfo.mapLayer.length != 0) {
      options.value = wmtsStore.wmtsInfo.mapLayer.map((item) => {
        return {
          label: item.Title,
          key: item.Identifier,
          children: item.TileMatrixSet.map((matrix) => ({
            label: matrix.TileMatrixSetName,
            key: matrix.TileMatrixSetName
          }))
        }
      })
      selectedValue.value = options.value[0].children[0].label
    }
  }
)
watch(
  () => appStore.showTabs,
  () => {
    appStore.showTabs ? (adaptHeight.value += 45) : (adaptHeight.value -= 45)
  },
  { immediate: true }
)
watch(
  () => appStore.showFooter,
  () => {
    appStore.showFooter ? (adaptHeight.value += 40) : (adaptHeight.value -= 40)
  },
  { immediate: true }
)

onMounted(() => {
  window.addEventListener('resize', handleResize)
  initViewer()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <n-card class="flex-1">
    <n-grid :x-gap="0" :y-gap="8" :cols="2">
      <n-gi>
        <n-flex>
          <n-input-group>
            <n-input v-model:value="wmtsURL" placeholder="请输入WMTS能力文档地址" />
            <n-button type="primary" :loading="loading" @click="load">
              <template #icon>
                <icon-park-outline-loading />
              </template>
              加载
            </n-button>
          </n-input-group>
        </n-flex>
      </n-gi>
      <n-gi>
        <n-flex class="max-w-[240px] ml-auto">
          <n-tree-select :options="options" placeholder="请选择要加载的地图矩阵集合" v-model:value="selectedValue" @update:value="handleUpdateValue" check-strategy="child" />
        </n-flex>
      </n-gi>
    </n-grid>
  </n-card>
  <n-card :style="{ height: `${computedHeight}px` }" class="flex-1 mt-2">
    <div id="SuperMap3DContainer" class="absolute-full"></div>
    <Loading v-if="addLoading" />
  </n-card>
</template>
